<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="机型" name="first">
        <div class="searchBox">
          <span>时间：</span>
          <el-date-picker
            v-model="deviceListModel.date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
          <el-button type="primary" class="query-btn" @click="fetchDeviceData">
            搜索
          </el-button>
        </div>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" style="margin-top: 25px;">
            <div
              id="deviceEcharts"
              style="width:100%; height:400px; border: 1px solid #EBEEF5;"
            />
          </el-col>
          <el-col :xs="24" :sm="12" style="margin-top: 25px;">
            <el-table
              v-loading="deviceListModel.loading"
              :data="deviceListModel.data"
              stripe
              style="width: 100%"
              border
              height="400"
            >
              <el-table-column prop="name" label="机型" width="180" />
              <el-table-column prop="value" label="启动次数" width="180" />
              <el-table-column prop="rate" label="启动次数(占比)" />
            </el-table>
            <el-pagination
              layout="prev, pager, next"
              :current-page.sync="deviceListModel.currentPage"
              :total="deviceListModel.total"
              @current-change="fetchDeviceData"
            />
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="操作系统" name="second">
        <div class="searchBox">
          <span>时间：</span>
          <el-date-picker
            v-model="osListModel.date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
          <el-button type="primary" class="query-btn" @click="fetchOsData">
            搜索
          </el-button>
        </div>

        <div style="margin-top: 25px;">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <div
                id="osEcharts"
                style="width:100%; height:400px; border: 1px solid #EBEEF5;"
              />
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-table
                v-loading="osListModel.loading"
                :data="osListModel.data"
                stripe
                style="width: 100%"
                height="400"
                border
              >
                <el-table-column prop="osName" label="操作系统" width="180" />
                <el-table-column prop="osVal" label="启动次数" width="180" />
                <el-table-column prop="rate" label="启动次数(占比)" />
              </el-table>
              <el-pagination
                layout="prev, pager, next"
                :current-page.sync="osListModel.currentPage"
                :total="osListModel.total"
                @current-change="fetchOsData"
              />
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  data() {
    const now = new Date()
    const aWeekAgo = new Date()
    aWeekAgo.setDate(now.getDate() - 7)
    return {
      deviceEcharts: null,
      osEcharts: null,
      activeName: 'first',
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      deviceListModel: {
        loading: true,
        currentPage: 1,
        start: 0,
        length: 10,
        total: 1,
        data: [],
        search: {},
        date: [aWeekAgo, now],
        echartsOptions: {
          title: {
            text: '启动次数',
            textStyle: {
              fontSize: '12',
              fontWeight: 'lighter'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: 100
          },
          xAxis: {
            type: 'value',
            name: '次数',
            axisLabel: {
              formatter: '{value}'
            }
          },
          yAxis: {
            type: 'category',
            inverse: true,
            data: []
          },
          series: [
            {
              name: '启动次数',
              type: 'bar',
              data: [],
              label: {
                normal: {
                  show: true
                }
              }
            }
          ]
        }
      },
      osListModel: {
        loading: true,
        currentPage: 1,
        start: 0,
        length: 10,
        total: 1,
        data: [],
        search: {},
        date: [aWeekAgo, now],
        echartsOptions: {
          title: {
            text: '启动次数',
            textStyle: {
              fontSize: '12',
              fontWeight: 'lighter'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: 100
          },
          xAxis: {
            type: 'value',
            name: '次数',
            axisLabel: {
              formatter: '{value}'
            }
          },
          yAxis: {
            type: 'category',
            inverse: true,
            data: []
          },
          series: [
            {
              name: '启动次数',
              type: 'bar',
              data: [],
              label: {
                normal: {
                  show: true
                }
              }
            }
          ]
        }
      }
    }
  },
  mounted() {
    const echarts = require('echarts')
    const deviceEchartsElement = document.getElementById('deviceEcharts')
    this.deviceEcharts = echarts.getInstanceByDom(deviceEchartsElement)
    if (!this.deviceEcharts) {
      this.deviceEcharts = echarts.init(deviceEchartsElement)
      this.deviceEcharts.setOption(this.deviceListModel.echartsOptions)
    }

    const osEchartsElement = document.getElementById('osEcharts')
    this.osEcharts = echarts.getInstanceByDom(osEchartsElement)
    if (!this.osEcharts) {
      this.osEcharts = echarts.init(osEchartsElement)
      this.osEcharts.setOption(this.osListModel.echartsOptions)
    }

    this.fetchDeviceData()
  },
  methods: {
    fetchDeviceData() {
      const self = this
      const param = {
        start:
          (this.deviceListModel.currentPage - 1) * this.deviceListModel.length,
        length: this.deviceListModel.length,
        query: {}
      }
      const date = this.deviceListModel.date
      if (date && date.length === 2) {
        param.query.startDate = window.formatter.formatDateTime(date[0])
        param.query.endDate = window.formatter.formatDateTime(date[1])
      }
      self.deviceListModel.loading = true
      request({
        url: '/mobile/mobileUserLoginLog/queryUserDevice',
        data: param,
        method: 'POST'
      }).then(res => {
        const { data, pages, startIndex } = res
        self.deviceListModel.data = data
        self.deviceListModel.total = pages
        self.deviceListModel.start =
          (startIndex - 1) * self.deviceListModel.length
        self.deviceListModel.echartsOptions.series[0].data = []
        self.deviceListModel.echartsOptions.yAxis.data = []
        if (Array.isArray(data)) {
          for (let i = 0; i < data.length; i++) {
            const item = data[i]
            self.deviceListModel.echartsOptions.series[0].data.push(item.value)
            self.deviceListModel.echartsOptions.yAxis.data.push(item.name)
          }
        }
        self.deviceListModel.loading = false

        self.deviceEcharts.setOption(self.deviceListModel.echartsOptions)
        self.deviceEcharts.resize()
      })
    },
    fetchOsData() {
      const self = this
      const param = {
        start: (this.osListModel.currentPage - 1) * this.osListModel.length,
        length: this.osListModel.length,
        query: {}
      }
      const date = this.osListModel.date
      if (date && date.length === 2) {
        param.query.startDate = date[0].format('yyyy-MM-dd hh:mm:ss')
        param.query.endDate = date[1].format('yyyy-MM-dd hh:mm:ss')
      }
      self.osListModel.loading = true
      request({
        url: '/mobile/mobileUserLoginLog/queryUserOs',
        data: param,
        method: 'POST'
      }).then(res => {
        const { data, pages, startIndex } = res
        self.osListModel.data = data
        self.osListModel.total = pages
        self.osListModel.start = (startIndex - 1) * self.osListModel.length

        self.osListModel.echartsOptions.series[0].data = []
        self.osListModel.echartsOptions.yAxis.data = []
        if (Array.isArray(data)) {
          for (let i = 0; i < data.length; i++) {
            const item = data[i]
            self.osListModel.echartsOptions.series[0].data.push(item.osVal)
            self.osListModel.echartsOptions.yAxis.data.push(item.osName)
          }
        }
        self.osListModel.loading = false

        self.osEcharts.setOption(self.osListModel.echartsOptions)
        self.osEcharts.resize()
      })
    },
    handleClick(tab, event) {
      if (tab.name === 'second') {
        this.fetchOsData()
      } else {
        this.fetchDeviceData()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.searchBox {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  .query-btn {
    margin-left: 10px;
  }
}
</style>
